import {Tile} from "./tile.mjs";
import {Rand} from "../utils/rand.mjs";
import {MyArray} from "../utils/array.mjs";
import {Matrix} from "../utils/matrix.mjs";

export class GameMap {
    tileArray

    constructor(container, mapSize) {
        this.mapSize = mapSize
        this.mapWidth = mapSize.width
        this.mapHeight = mapSize.height

        container.replaceChildren()
        this.tileArray = Matrix.initByMap(
            mapSize.height, mapSize.width,
            _ => new Tile(container))
        // this.tileArray = this.#build3(container)

        this.gemPos = new Rand().position(this.mapSize, Math.random)
    }

    initState(peekArray) {
        let [x, y] = this.gemPos
        this.tileArray[x][y].setStyleClasses('diamond')

        this.addState(peekArray, 'peek')

        let [i, j] = MyArray.getCenterIdx(peekArray)
        this.addState(peekArray[i][j], 'player')
    }

    #filter(arr) {
        return arr.filter(
            ([x, y]) => {
                return x >= 0 && x < this.mapHeight
                    && y >= 0 && y < this.mapWidth
            }
        )
    }

    #normPosSet(posSet) {
        let dim = MyArray.getDim(posSet)
        switch (dim) {
            case 1:
                posSet = [posSet]
                break
            case 3:
                posSet = posSet.flat()
        }
        return this.#filter(posSet)
    }

    addState(posSet, ...states) {
        this.#normPosSet(posSet).forEach(([x, y]) =>
            this.tileArray[x][y].addStyleClasses(...states)
        )
    }

    removeState(posSet, ...states) {
        this.#normPosSet(posSet).forEach(([x, y]) =>
            this.tileArray[x][y].removeStyleClasses(...states)
        )
    }

    toggleState(posSet, ...states) {
        this.#normPosSet(posSet).forEach(([x, y]) =>
            this.tileArray[x][y].toggleStyleClasses(...states)
        )
    }
}
